<template>
    <div class="header">
        <el-input
            class="w-50 m-2"
            placeholder="请输入联系人名称"
            :prefix-icon="Search"
            v-model="text"
            @input="handleSearch"
        />
        <el-button type="success" :icon="Plus" circle  @click="handleAddContact" />
  </div>
  <ContactAddDialog v-show="chatStor.state.showAddContactsDialog===true" />
</template>

<script setup lang="ts">
import ContactAddDialog from '@/components/chat/ContactAddDialog.vue';
import {Search,Plus} from '@element-plus/icons-vue';
import {chatStore} from '@/stores/disk/chat'
import { ref } from 'vue'
const chatStor=chatStore()
const text=ref('')
const handleAddContact = () => {
    chatStor.updateShowAddContactsDialog(true)
}

//搜索联系人
const handleSearch = async () => {
   if (text.value.trim() === '') {
    chatStor.updateActiveContactId(null);
   }else{
    const searchText = text.value.toLowerCase();
    // 找到匹配的联系人
    const matchedContacts =chatStor.state.contacts.filter(contact=> 
        contact.contactName.toLowerCase().includes(searchText)
    );
     // 将匹配的联系人放在最前面
     const filteredContacts = [
          ...matchedContacts,
          ...chatStor.state.contacts.filter(contact => 
            !contact.contactName.toLowerCase().includes(searchText)
          )
     ];
     chatStor.updateContactInfo(filteredContacts);
     // 找到第一个匹配的联系人并设置为选中状态
     if (matchedContacts.length > 0) {
        chatStor.updateActiveContactId(matchedContacts[0].id); 
     } else {
        chatStor.updateActiveContactId(null); // 如果没有匹配的联系人，清空选中状态
     }
   }
}

</script>

<style scoped>
.header {
    display: flex;
    margin-bottom: 10px;
}
</style>